<?php

namespace App\Models;

use App\Observers\CategoryObserver;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Category extends Model
{
    use ModelTree;
    protected $table = 'yida_category';


    protected static function booted()
    {
        parent::booted(); // TODO: Change the autogenerated stub
        static::created(function ($category){
            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_insert'=>$category->toArray()];
            Log::channel("LaravelInsert")->error("添加操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"insert",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "添加操作",
                'table' => "yida_category"
            ]);
        });
        static::updated(function ($category){

            $role = Admin::user()->roles->toArray();
            if($category->status == 0){

                $data = $category->toArray();
                if($role[0]['pivot']['role_id'] != 1){
                    //更改admin_role_menu表数据
                    $menu = DB::table("admin_menu")->where("id",$data['menu_id'])->select('id','parent_id')->get()->toArray();
                    DB::table("admin_menu")->where('id',$data['menu_id'])->update(['status'=>0]);
                    self::MenuDelete($menu,$role[0]['pivot']['role_id']);
                }
            }else{

                $data = $category->toArray();
                if($role[0]['pivot']['role_id'] != 1){

                    $menu = DB::table("admin_menu")->where("id",$data['menu_id'])->select('id','parent_id')->get()->toArray();
                    DB::table("admin_menu")->where('id',$data['menu_id'])->update(['status'=>1]);
                    self::MenuSave($menu,$role[0]['pivot']['role_id']);
                }
            }
            Cache::store('redis')->delete('menu');

            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_update'=>$category->toArray()];
            Log::channel("LaravelUpdate")->error("更新操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"update",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "更新操作",
                'table' => "yida_category"
            ]);
        });
        static::deleted(function ($category){

            $role = Admin::user()->roles->toArray();

            if($role[0]['pivot']['role_id'] != 1){
                //更改admin_role_menu表数据
                $menu = DB::table("admin_menu")->where("id",$data['menu_id'])->select('id','parent_id')->get()->toArray();
                DB::table("admin_menu")->where('id',$data['menu_id'])->update(['status'=>0]);
                self::MenuDelete($menu,$role[0]['pivot']['role_id']);
            }

            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_delete'=>$category->toArray()];
            Log::channel("LaravelDelete")->error("删除操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"delete",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "删除操作",
                'table' => "yida_category"
            ]);
        });

    }


    /**
     * 递归添加主键修改
     * @author chen
     * @param $menu
     * @param $roleId
     */
    public static function MenuSave($menu,$roleId){

        foreach ($menu as $value){

            //插入admin_role_menu表数据
            $sql = "insert into admin_role_menu (role_id,menu_id)
                    values ({$roleId},{$value->id})
                    on duplicate key update
                    role_id = {$roleId},
                    menu_id = {$value->id}";
            DB::select($sql);
            DB::table("admin_menu")->where("id",$value->id)->update(['status' => 1]);
            $data = DB::table("admin_menu")->where("parent_id",$value->id)->get()->toArray();
            if($data){
                self::MenuSave($data,$roleId);
            }

        }

    }


    /**
     * 递归删除对应的菜单
     * @author chen
     * @param $menu
     * @param $roleId
     */
    public static function MenuDelete($menu,$roleId){

        foreach ($menu as $value){

            DB::table('admin_role_menu')->where('role_id',$roleId)->where("menu_id",$value->id)->delete();
            DB::table("admin_menu")->where("id",$value->id)->update(['status' => 0]);
            $data = DB::table("admin_menu")->where('parent_id',$value->id)->get()->toArray();
            if($data){
                self::MenuDelete($data,$roleId);
            }

        }
        Cache::store('redis')->delete('menu');

    }
}
